﻿using AutoMapper;

using Microsoft.IdentityModel.Tokens;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ZFB.Common;
using ZFB.DTO;
using ZFB.IServices;
using ZFB.Models;
using ZFB.Repository.AdminUser;
using ZFB.Repository.Attachments;

namespace ZFB.Services
{
    public class AttachmentsServices : IAttachmentsServices
    {
        public IAttachmentsRepository attachmentsRepository;
        private readonly IMapper mapper;
        public AttachmentsServices(IAttachmentsRepository attachmentsRepository, IMapper mapper)
        {
            this.attachmentsRepository = attachmentsRepository;
            this.mapper = mapper;
        }

        public async Task<ApiResult> GetAllAsync()
        {
            var data = await attachmentsRepository.GetListAsync();
            if (data.IsNullOrEmpty())
            {
                return new ApiResult("获取失败!");
            }
            else
            {
                var dto = mapper.Map<List<AttachmentDTO>>(data);
                return new ApiResult(dto);
            }
        }

        public async Task<ApiResult> AddAsync(string name, string icon)
        {
            if (await attachmentsRepository.IsExistAsync(e => e.Name == name)) return new("设施已存在");
            var atta = new T_Attachments
            {
                Name = name,
                IconName = icon
            };
            var res = await attachmentsRepository.AddAsync(atta);
            return res <= 0 ? new ApiResult("添加失败！") : new ApiResult();
        }

        public async Task<ApiResult> DeleteAsync(long id)
        {
            if (!await attachmentsRepository.IsExistAsync(e => e.Id == id)) return new ApiResult("id不存在");
            var res = await attachmentsRepository.UpdateIsDeleteAsync(e => e.Id == id);
            return res <= 0 ? new ApiResult("删除失败！") : new ApiResult();

        }
    }
}
